package org.elec.mac.utils;

import org.elec.mac.entity.SessionUser;
import org.elec.mac.entity.SysMenu;
import org.elec.mac.entity.SysUser;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bean on 2017/5/26.
 */
public class MenuUtil {

    /**
     * 生成菜单
     * @param request
     * @param manager
     * @param sessionUser
     */
    public void initMenu(HttpServletRequest request, EhCacheCacheManager manager, SessionUser sessionUser) {
        Cache authorityCache = manager.getCache("authorityCache");
        String username = authorityCache.get(sessionUser.getToken(), String.class);
        // 获取用户角色
        Cache userCache = manager.getCache("userCache");
        SysUser sysUser = userCache.get(username, SysUser.class);
        Cache roleUserCache = manager.getCache("roleUserCache");
        Long roleId = roleUserCache.get(sysUser.getId(), Long.class);
        //
        Cache roleMenuCache = manager.getCache("roleMenuCache");
        List<SysMenu> menuList = roleMenuCache.get(roleId, ArrayList.class);
        //
        List<SysMenu> menus = new ArrayList<SysMenu>();
        SysMenu startMenu = new SysMenu();
        startMenu.setId(0L);
        initMenuList(startMenu, menuList, menus);
        // 加载菜单
        Cache userMenuCache = manager.getCache("userMenuCache");
        userMenuCache.put(username, menuList);
    }

    /**
     * 组装菜单
     * @param startMenu
     * @param menuList
     * @param menus
     */
    public void initMenuList(SysMenu startMenu, List<SysMenu> menuList, List<SysMenu> menus) {
        Long startId = startMenu.getId();
        List<SysMenu> menuArray = new ArrayList<>();
        for(SysMenu menu : menuList){
            if(menu.getParentMenuId() != null && menu.getParentMenuId() == startId) {
                menuArray.add(menu);
            }
        }
        if(startMenu != null && startMenu.getId() != 0) {
            menus.add(startMenu);
        }
        if(menuArray.size() > 0) {
            orderMenuList(menuArray);
            for(SysMenu menu : menuArray){
                initMenuList(menu, menuList, menus);
            }
        }
    }

    /**
     * 菜单排序
     * @param menus
     */
    public void orderMenuList(List<SysMenu> menus) {
        for(int i = 0; i < menus.size(); i++){
            for(int j = 0; j < menus.size() - (i + 1); j++){
                SysMenu menu1 = menus.get(j);
                SysMenu menu2 = menus.get(j + 1);
                int order1 = menu1.getShowOrder();
                int order2 = menu2.getShowOrder();
                if(order1 > order2){
                    menus.set(j, menu2);
                    menus.set(j + 1, menu1);
                }
            }
        }
    }
}
